/**
 * Created by DevilsEyes on 2016/2/13.
 */
'use strict';

var express = require('express');
var multer = require('multer');
var $file = require('../midware/file');
var upload = multer({dest: '../files/'});
var router = express.Router();

// var $user = require('../midware/user');
var $session = require('../midware/session');


router.get(/^\/view\/.*/, function (req, res, next) {
    var path = '../files' + req.path.replace('/view', '');  // 文件存储的路径
    res.download(path);
});

router.get(/^\/download\/.*/, function (req, res, next) {
    // console.log(req.path);
    // var path = '../files' + req.path.replace('/download', '');  // 文件存储的路径

    var path = (req.path).replace('/download/', '');  // 文件存储的路径
    $file.getFileByPath(path)
        .then((file)=> {
            res.setHeader("Content-Type", file.type);
            res.download('../files/' + path, file.name);
        })
        .catch((e)=> {
            res.json(e);
        });
});

router.post('/upload', upload.array('file'), function (req, res) {

    let file = req.files[0];
    if (!file) {
        return res.json({
            code: 9999,
            msg: '没有文件'
        })
    }
    $file
        .save({
            name: file.originalname,
            type: file.mimetype,
            path: file.filename
        })
        .then((file)=> {
            res.json({
                code: 0,
                file: {
                    path: file.path
                }
            });
        });

});

router.get('/list', function (req, res, next) {

    let cookies = req.cookies;
    let ssid = cookies.ssid;

    new Promise((O, X)=> {
        O();
    })
        .then(()=> {
            $session.isAdmin(ssid);

            return $file.getAll();
        })
        .then((files)=> {
            res.json({
                files: files
            });
        })
        .catch((e)=> {
            res.json({
                code: e.code,
                msg: e.msg
            });
        });
});

module.exports = router;